package com.jhws.business.owner.service;

import com.jhws.business.comm.bo.TblBuildingDimBo;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.business.face.bo.FaceConstant;
import com.jhws.business.face.service.FaceService;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.business.local.service.LocalService;
import com.jhws.business.owner.bo.OwnerConstant;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.common.base.bo.Global;
import com.jhws.core.db.BaseDao;
import com.jhws.sys.appUser.bo.SipAccountConstant;
import com.jhws.sys.appUser.bo.TblSipAcountBindings;
import com.jhws.sys.appUser.service.ITblSipAcountDimService;
import com.jhws.util.commUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

public class TblOwnerDimServiceSpringImpl implements ITblOwnerDimService {
    @Resource
    private BaseDao BaseDao;
    @Resource
    private ITblSipAcountDimService ITblSipAcountDimService;
    @Resource
    private ITblBuildingDimService tblBuildingDimService;
    @Resource
    private FaceService faceService;
    @Resource
    private LocalService localService;

    public void update(TblOwnerDimBo bo) throws Exception {
        bo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
        BaseDao.update(bo);
    }

    public void save(TblOwnerDimBo bo) throws Exception {
        bo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
        String accountId = ITblSipAcountDimService.addSipAccount(bo.getOwnerMob(), Global.DEFAULT_USER_PWD, SipAccountConstant.TYPE_MOBILE, false);
        bo.setSipAcountId(accountId);
        BaseDao.saveOrUpdate(bo);
    }

    public List<TblOwnerDimBo> findTblOwnerDimByWhere(String whereStr) throws Exception {
        if (localService.isLanMode()) {
            whereStr += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
        }
        return BaseDao.findList("from TblOwnerDimBo " + whereStr);
    }

    @Override
    public TblOwnerDimBo findTblOwnerDimByMobOrRoomInfo(String mob, String roomInfo) throws Exception {
        String whereStr = "from TblOwnerDimBo where owner_mob = '" + mob + "' and room_info_num = '" + roomInfo + "'";
        if (localService.isLanMode()) {
            whereStr += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
        }
        // TODO Auto-generated method stub
        List<TblOwnerDimBo> tList = BaseDao.findList(whereStr);
        if (tList != null && tList.size() > 0) {
            return tList.get(0);
        }
        return null;
    }

    @Override
    public int findOwnerCountByWhere(String where) {
        if (localService.isLanMode()) {
            where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "'";
        }
        return BaseDao.getCountByHql("select count(*) from TblOwnerDimBo " + where).intValue();
    }

    public Map<String, Object> findOwnerList(Map param) throws Exception {
        String whereClause = "1=1 ";

        if (localService.isLanMode()) {
            whereClause += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }

        String ownerName = MapUtils.getString(param, "ownerName", "");
        if (StringUtils.isNotEmpty(ownerName)) {
            whereClause += " and owner_name like '%" + param.get("ownerName") + "%'";
        }

        String ownerMob = MapUtils.getString(param, "ownerMob", "");
        if (StringUtils.isNotEmpty(ownerMob)) {
            whereClause += " and owner_mob = '" + ownerMob + "'";
        }

        String commCode = MapUtils.getString(param, "commCode", "");
        if (StringUtils.isNotEmpty(commCode)) {
            whereClause += " and comm_code in (" + commUtil.commCodesToSqlStr(commCode) + ")";
        }

        String areaCode = MapUtils.getString(param, "areaCode", "");
        if (StringUtils.isNotEmpty(areaCode)) {
            whereClause += " and area_code = '" + areaCode + "'";
        }
        String buildingCode = MapUtils.getString(param, "buildingCode", "");
        if (StringUtils.isNotEmpty(buildingCode)) {
            whereClause += " and building_code = '" + buildingCode + "'";
        }
        String unitCode = MapUtils.getString(param, "unitCode", "");
        if (StringUtils.isNotEmpty(unitCode)) {
            whereClause += " and unit_code = '" + unitCode + "'";
        }
        String roomCode = MapUtils.getString(param, "roomCode", "");
        if (StringUtils.isNotEmpty(roomCode)) {
            whereClause += " and room_code = '" + roomCode + "'";
        }
        String applyType = MapUtils.getString(param, "applyType", "");
        if (StringUtils.isNotEmpty(applyType)) {
            whereClause += " and apply_type = '" + applyType + "'";
        } else {

            //如果是超级管理员将别墅业主也返回，便于查找问题
            String villaType = "";
            if (SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
                villaType = " or apply_type = '" + OwnerConstant.OWNER_TYPE_VILLA + "' ";
            }

            /* 假如没有带业主类型,则返回业主与家属类型的,不包括申请中的状态, 这样这个接口就不可能查询整表数据了 */
            whereClause += " and (apply_type = '" + OwnerConstant.OWNER_TYPE + "' or apply_type = '" + OwnerConstant.OWNER_TYPE_FAMILY + "' or apply_type = '" + OwnerConstant.OWNER_TYPE_RENTER + "' " + villaType + " )";
        }

        String hql = "select new map(owner.ownerCode as ownerCode,owner.ownerName as ownerName,owner.ownerMob as ownerMob," +
                "owner.roomInfo as roomInfo,owner.commName as commName,owner.lastModify as lastModify,owner.applyType as applyType,owner.isEnable as isEnable,owner.isSynch as isSynch) from TblOwnerDimBo as owner where " + whereClause;
        return BaseDao.queryPage(hql);
    }

    /**
     * 获取小区的业主数据导出excel表用
     *
     * @param param
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> findOwnerListForExport(Map param) throws Exception {
        String whereClause = "1=1 ";

        if (localService.isLanMode()) {
            whereClause += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }

        String commCode = MapUtils.getString(param, "commCode", "");
        if (StringUtils.isNotEmpty(commCode)) {
            whereClause += " and comm_code in (" + commUtil.commCodesToSqlStr(commCode) + ")";
        }

        String areaCode = MapUtils.getString(param, "areaCode", "");
        if (StringUtils.isNotEmpty(areaCode)) {
            whereClause += " and area_code = '" + areaCode + "'";
        }
        String buildingCode = MapUtils.getString(param, "buildingCode", "");
        if (StringUtils.isNotEmpty(buildingCode)) {
            whereClause += " and building_code = '" + buildingCode + "'";
        }
        String unitCode = MapUtils.getString(param, "unitCode", "");
        if (StringUtils.isNotEmpty(unitCode)) {
            whereClause += " and unit_code = '" + unitCode + "'";
        }
        String roomCode = MapUtils.getString(param, "roomCode", "");
        if (StringUtils.isNotEmpty(roomCode)) {
            whereClause += " and room_code = '" + roomCode + "'";
        }

        String applyType = MapUtils.getString(param, "applyType", "");
        if (StringUtils.isNotEmpty(applyType)) {
            whereClause += " and apply_type = '" + applyType + "'";
        } else {

            //如果是超级管理员将别墅业主也返回，便于查找问题
            String villaType = "";
            if (SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
                villaType = " or apply_type = '" + OwnerConstant.OWNER_TYPE_VILLA + "' ";
            }

        /* 假如没有带业主类型,则返回业主与家属类型的,不包括申请中的状态, 这样这个接口就不可能查询整表数据了 */
            whereClause += " and (apply_type = '" + OwnerConstant.OWNER_TYPE + "' or apply_type = '" + OwnerConstant.OWNER_TYPE_FAMILY + "' or apply_type = '" + OwnerConstant.OWNER_TYPE_RENTER + "' " + villaType + " )";
        }

        String sql = "select owner_name as ownerName,owner_mob as ownerMob,room_info as roomInfo,room_info_num as roomInfoNum from tbl_owner_dim where " + whereClause;

        List retlist = BaseDao.findListBySql(sql);
        return retlist;
    }

    /**
     * 查找业主表中类型为管理员的数据
     *
     * @param param
     * @return
     */
    public Map findManagerList(Map param) {
        String whereClause = "1=1 and apply_type = '" + OwnerConstant.OWNER_TYPE_PROPERTY_MANAGER + "' ";

        if (localService.isLanMode()) {
            whereClause += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }

        String commCode = MapUtils.getString(param, "commCode", "");
        if (StringUtils.isNotEmpty(commCode)) {
            whereClause += " and comm_code = '" + commCode + "'";
        }

        return BaseDao.queryPage("from TblOwnerDimBo where " + whereClause);
    }

    public TblOwnerDimBo findTblOwnerDimById(String ownerCode) {
        if (localService.isLanMode()) {
            return BaseDao.get(" from TblOwnerDimBo where is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' and owner_code='" + ownerCode + "'");
        }
        return BaseDao.get(TblOwnerDimBo.class, ownerCode);
    }

    public void removeDim(String ownerCode) throws Exception {
        if (localService.isLanMode()) {
            BaseDao.executeHql("update TblOwnerDimBo set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where owner_code='" + ownerCode + "'");
        } else {
            BaseDao.delete(TblOwnerDimBo.class, ownerCode);
        }
        faceService.updateFacesState(ownerCode, FaceConstant.STATE_CODE.delete.ordinal());
    }

    public String OPCheckFormOwnerLegal(TblOwnerDimBo owner) throws Exception {
        // 从数据库查询用户输入的身份证号是否使用
        List<TblOwnerDimBo> ownlist;
        String retStr = null;
        String RoomInfoNum = owner.getRoomInfoNum();

        String where = "where 1=1 and comm_code = '" + owner.getCommCode() + "' and area_name = '" + Integer.valueOf(owner.getAreaCode()) + "' and building_name = '"
                + Integer.valueOf(owner.getBuildingCode()) + "'";

        List<TblBuildingDimBo> bos = tblBuildingDimService.findTblBuildingDimByWhere(where);
        if (bos.size() == 0)
            return "楼宇：" + owner.getAreaCode() + "栋" + owner.getBuildingCode() + "单元不存在！";


        if (!StringUtils.isEmpty(owner.getOwnerMob())) {

            ownlist = findTblOwnerDimByWhere("where 1=1 and owner_mob = '" + owner.getOwnerMob() + "'");

            List<TblSipAcountBindings> blist = ITblSipAcountDimService.getBindingsByUser(owner.getOwnerMob());
            for (TblSipAcountBindings tblSipAcountBinding : blist) {
                if (RoomInfoNum.equals(tblSipAcountBinding.getBinding())) {
                    retStr = "该业主已经具有 " + RoomInfoNum + " 的呼叫绑定权限，确认业主是否已存在";
                    return retStr;
                }
            }

            if (null != ownlist && ownlist.size() > 0) {
                for (TblOwnerDimBo tblOwnerDimBo : ownlist) {

                    if (!tblOwnerDimBo.getOwnerName().equals(owner.getOwnerName())) {
                        String ownerType = tblOwnerDimBo.getApplyType() == OwnerConstant.OWNER_TYPE_PROPERTY_MANAGER ? "管理员" : "业主";
                        retStr = "该手机号已被  " + ownerType + tblOwnerDimBo.getOwnerName() + "绑定，请确认业主名称,然后重新输入!";
                        return retStr;
                    }

                    /* 假设该业主正在申请中, 则删除掉申请记录 */
                    if (tblOwnerDimBo.getRoomInfoNum().equals(RoomInfoNum) && tblOwnerDimBo.getApplyType() == OwnerConstant.OWNER_TYPE_APPLYING) {
                        removeDim(tblOwnerDimBo.getOwnerCode());
                    }

                }
            }
        }
        return retStr;
    }

    @Override
    public String checkFormOwnerLegal(TblOwnerDimBo ownerDimBo) throws Exception {
        // 从数据库查询用户输入的身份证号是否使用
        List<TblOwnerDimBo> ownlist;
        String retStr = null;
        String roomInfoNum = ownerDimBo.getCommCode() + ownerDimBo.getAreaCode() + ownerDimBo.getBuildingCode() + ownerDimBo.getUnitCode() +
                ownerDimBo.getRoomId();

        String where = "where 1=1 and comm_code = '" + ownerDimBo.getCommCode() + "' and area_name = '" + Integer.valueOf(ownerDimBo.getAreaCode()) + "' and building_name = '"
                + Integer.valueOf(ownerDimBo.getBuildingCode()) + "'";
        List<TblBuildingDimBo> bos = tblBuildingDimService.findTblBuildingDimByWhere(where);
        if (bos.size() == 0)
            return "楼宇：" + ownerDimBo.getAreaCode() + "栋" + ownerDimBo.getBuildingCode() + "单元不存在！";

        ownlist = findTblOwnerDimByWhere("where 1=1 and owner_mob = '" + ownerDimBo.getOwnerMob() + "'");
        if (null != ownlist && ownlist.size() > 0) {
            for (TblOwnerDimBo tblOwnerDimBo : ownlist) {
                if (!tblOwnerDimBo.getOwnerName().equals(ownerDimBo.getOwnerName())) {
                    String ownerType = tblOwnerDimBo.getApplyType() == OwnerConstant.OWNER_TYPE_PROPERTY_MANAGER ? "管理员" : "业主";
                    retStr = "该手机号已被  " + ownerType + tblOwnerDimBo.getOwnerName() + "  绑定，请重新输入!";
                    return retStr;
                } else if (tblOwnerDimBo.getRoomInfoNum().equals(ownerDimBo.getRoomInfoNum())) {
                    if (ownerDimBo.getApplyType() == OwnerConstant.OWNER_TYPE_APPLYING)
                        retStr = "该业主之前已自主提交过该房间申请，请到申请列表中查看";
                    else
                        retStr = "该业主已经绑定了此房间";
                    return retStr;
                }
            }
        }

        List<TblSipAcountBindings> blist = ITblSipAcountDimService.getBindingsByUser(ownerDimBo.getOwnerMob());
        for (TblSipAcountBindings tblSipAcountBinding : blist) {
            if (roomInfoNum.equals(tblSipAcountBinding.getBinding())) {
                retStr = "该业主已经具有 " + roomInfoNum + " 的呼叫绑定权限";
                return retStr;
            }
        }
        return retStr;
    }
}
